package pers.vic.third.tbk;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NTbkItem;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;

import pers.vic.base.craw.CrawlConnect;

/**
 * 淘宝客的调用接口的工具类
 * 
 * @author VIC
 *
 */
public class TbkUtils {

	private static Logger logger = LoggerFactory.getLogger(TbkUtils.class);

	static String api_url = "http://gw.api.taobao.com/router/rest";
	static String appkey = "24896118";
	static String secret = "bf6e5bcf0abe78177609552826277f43";
	// 图文详情
//	static String CONETNT_URL = "https://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?type=jsonp&dataType=jsonp2";
	static String CONETNT_URL = "https://hws.m.taobao.com/cache/desc/5.0?id=";
	/**
	 * 淘宝客商品详情
	 * 
	 * @param itemId
	 */
	public static NTbkItem tbkDetail(String itemId) {
		try {
			TbkItemInfoGetResponse r = detail(itemId);
			List<NTbkItem> list = r.getResults();
			if (list != null) {
				return list.get(0);
			}
		} catch (Exception e) {
			logger.error("获取淘宝客商品详情出错");
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;
	}

	/**
	 * 商品详情
	 * 
	 * @return
	 * @throws ApiException
	 */
	public static TbkItemInfoGetResponse detail(String itemId) throws ApiException {
		TaobaoClient client = new DefaultTaobaoClient(api_url, appkey, secret);
		TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
		req.setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url");
		req.setPlatform(1L);
		req.setNumIids(itemId);
		TbkItemInfoGetResponse rsp = client.execute(req);
		return rsp;
	}

	/**
	 * 单个商品详情
	 * 
	 * @param itemId
	 * @return
	 */
	public static NTbkItem getItem(String itemId) {
		if (StringUtils.isEmpty(itemId))
			return null;
		try {
			TbkItemInfoGetResponse res = detail(itemId);
			if (res != null) {
				List<NTbkItem> list = res.getResults();
				if (!CollectionUtils.isEmpty(list)) {
					return list.get(0);
				}
			}
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

		return null;
	}

	/**
	 * 获得商品的多图逗号分隔。
	 */
	public static String getItemImages(String itemId) {
		if (StringUtils.isEmpty(itemId))
			return null;

		try {
			TbkItemInfoGetResponse res = detail(itemId);
			if (res != null) {
				List<NTbkItem> list = res.getResults();
				if (!CollectionUtils.isEmpty(list)) {
					List<String> images = list.get(0).getSmallImages();
					if (images != null) {
						return String.join(",", images);
					}
				}
			}
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;

	}

	/**
	 * 淘口令
	 * 
	 * @throws ApiException
	 */
	public static String taoToken(String link) {
		try {
			TaobaoClient client = new DefaultTaobaoClient(api_url, appkey, secret);
			TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
			req.setUserId("123");
			req.setText("省惠优选的");
			// req.setUrl("https://uland.taobao.com/coupon/edetail?e=bPemVgyIMQQN%2BoQUE6FNzI5OqDuV0th868MWT4uAMB0Q%2BsgjICc5SWWzSbDvM%2Bzoiu%2FgHta36OPoCOe3g3Ke33z%2F5lYwoL5ISB9Oxyt7%2BcDX18gaNN%2BIPg2wv9IT6u5QWPGZKFbQVU5I0DO2tQlGUOo%2FVaFxwr7TQzcTBs%2BWnXE%3D&af=1&pid=mm_132345716_45558477_622180547");
			req.setUrl(link);
			req.setExt("{}");
			TbkTpwdCreateResponse rsp = client.execute(req);

			return rsp.getData().getModel();
		} catch (Exception e) {
			logger.error("获取淘口令失败：api_url: {}", link);
		}
		return null;

	}

	/**
	 * 图文详情
	 *    https://hws.m.taobao.com/cache/desc/5.0?id=
	 *    http://w.huge98.top/addons/bsht_tbk/iidpic.php?&iid=
	 * @return
	 */
	static String  CONTENT_URL1 = "https://hws.m.taobao.com/cache/desc/5.0?id=";
	static String  CONTENT_URL2 = "http://w.huge98.top/addons/bsht_tbk/iidpic.php?&iid=";
	static Boolean flag = false;
	public static String content(String itemId) {
		try {
			JSONArray array = null;
			if(flag) {//使用  https://hws.m.taobao.com/cache/desc/5.0?id=
				flag = !flag;
				CrawlConnect con = con(CONTENT_URL1 + itemId);
				String text = con.getBodyText();
				JSONObject object = JSON.parseObject(text);
				logger.info("通过{}{}采集图文详情-->{}",CONTENT_URL1, itemId, object);
				if(object != null) {
					JSONObject wdescContent = object.getJSONObject("wdescContent");
					if(wdescContent != null) {
						array = wdescContent.getJSONArray("pages");
					}
				}
			}else {//使用  http://w.huge98.top/addons/bsht_tbk/iidpic.php?&iid=
				flag = !flag;
				CrawlConnect con = con(CONTENT_URL2 + itemId);
				String text = con.getBodyText();
				JSONObject object = JSON.parseObject(text);
				logger.info("通过{}{}采集图文详情-->{}",CONTENT_URL2, itemId, object);
				if(object != null) {
					JSONObject data = object.getJSONObject("data");
					if(data != null) {
						array = data.getJSONArray("images");
					}
				}
			}
			if(CollectionUtils.isNotEmpty(array)) {
				Set<String> set = new HashSet<String>();// 去重
				array.stream().forEach(img->{
					set.add( "<img src=\"" + String.valueOf(img) + "\"></img>");
				});
				return "<p>\n" + String.join("\n", set) + "\n</p>";
			}
			
			/*
			 * 从图片列表中转换版本
			 * String images = getItemImages(itemId);
			if(StringUtils.isNotEmpty(images)) {
				Set<String> set = new HashSet<String>();// 去重
				Arrays.asList(images.split(",")).stream().forEach(img->{
					set.add(img = "<img src=\"" + img + "\"></img>");
				});
				return "<p>\n" + String.join("\n", set) + "\n</p>";
			}*/
			/*
			 * https://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?type=jsonp&dataType=jsonp2 版本
			String data = "{item_num_id:" + itemId + "}";
			CrawlConnect con = con(CONETNT_URL).data("data", data);
			String text = con.getBodyText().replace(" ", "");
			String reg = "(https://img(.*?).jpg)";
			List<String> list = RegexUtil.getList(text, reg, 1);
			if (list == null)
				return null;
			Set<String> set = new HashSet<String>();// 去重
			list.stream().forEach(img -> {
				set.add(img = "<img src=\"" + img + "\"></img>");
			});
			return "<p>" + String.join("\n", set) + "</p>";
			
			
			*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected static CrawlConnect con(String url) {
		Connection conn = Jsoup.connect(url).ignoreContentType(true).timeout(5000);
		return new CrawlConnect(conn);
	}

	public static void main(String[] args) throws IOException {
//		System.out.println(content("10031645140"));
//		String s = con("http://hws.m.taobao.com/cache/wdesc/5.0/?id=529048526383").getHtml();
		
		System.out.println(content("10031645140"));
		System.out.println("--------------------------------------");
		System.out.println(content("564906644821"));
	}

}
